from django.shortcuts import render,redirect,reverse
from django.contrib.auth import login,logout,authenticate
from django.views.decorators.http import require_POST
from .forms import LoginForm,RegisterForm
from utils import restful,sms_send
from .models import User
from django.http import HttpResponse
from django.core.cache import cache
from utils.captcha.xfzcaptcha import Captcha
from io import BytesIO
# Create your views here.


def index(request):
    user = User.objects.create_user('18888888888','91wangfan','123123')

    return HttpResponse("OK")
@require_POST
def login_view(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        password = form.cleaned_data.get('password')
        remember = form.cleaned_data.get('remember')
        user = authenticate(request,username=telephone,password=password)
        if user:
            if user.is_active:
                login(request,user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                return restful.ok()
            else:
                return restful.auth_error(message="您的账号被冻结")
        else:
            return restful.params_error(message="用户名或者密码错误")
    else:
        errors = form.get_errors()
        #{"password":[],"telephone":[]}
        return restful.params_error(message=errors)

@require_POST
def register_view(request):
    form = RegisterForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        username  = form.cleaned_data.get('username')
        password  = form.cleaned_data.get('password1')
        user = User.objects.create_user(telephone=telephone,username=username,password=password)
        login(request,user)
        return restful.ok()
    else:
        return restful.params_error(message=form.get_errors())

#短信验证码
def sms_captcha(request):
    #/sms_catcha/?telephone=13888888888
    telephone = request.GET.get('telephone')
    print(telephone)
    code = Captcha.gene_text()
    print(code)
    cache.set(telephone,code,5*60)
    sms_send.send_sms(telephone,code)
    return restful.ok()




#图形验证码
def img_captcha(request):
    text,image = Captcha.gene_code()
    #BytesIO相当于一个管道 用来存储图片的流数据
    out = BytesIO()
    #调用Image的 save()方法 将图片保存在BytesIO中
    image.save(out,'png')

    #指针回到开始的位置
    out.seek(0)
    #out.read() 从io中读取已经存储的image 信息
    response = HttpResponse(content_type='image/png') #这是最终返回给浏览器的
    response.write(out.read()) #将它保存成图片
    response['Content-length'] = out.tell() #
    cache.set(text.lower(),text.lower(),5*60) #将图形验证码内容放到缓存中
    return response




def logout_view(request):
    logout(request)
    return redirect(reverse('news:index'))
